/**
 * @author        Nicolas Bottarini <nicolasbottarini@gmail.com>, 404 <http://www.proyecto404.com>
 * @version       $Rev: 3 $
 * @lastrevision  $Date: 2011-09-12 16:45:37 +0000 (Mon, 12 Sep 2011) $	 
 */
package com.proyecto404.core {
	import com.proyecto404.core.collections.Queue;
	
	import org.osflash.signals.ISignal;
	import org.osflash.signals.Signal;
	import org.osflash.signals.events.IEvent;

	public class JobQueue extends BaseObject {
		private var _queue:Queue;
		private var _allJobsExecuted:Signal;
		private var _progress:Signal;
		private var _error:Signal;
		
		public function JobQueue() {
			_allJobsExecuted = new Signal(EventArgs);
			_queue = new Queue();
			_progress = new Signal(EventArgs);
			_error = new Signal(EventArgs);
		}
		
		public function get progress():ISignal {
			return _progress;
		}
		
		public function get allJobsExecuted():ISignal {
			return _allJobsExecuted;
		}
		
		public function get error():ISignal {
			return _error;
		}
		
		public function addJob(job:IJob, jobExecutedCallback:Function = null):void {
			var item:JobItem = new JobItem(job, jobExecutedCallback);
			item.job.error.add(function(e:EventArgs):void {
				_error.dispatch(e);	
			});
			_queue.add(item);
		}
		
		public function execute():void {
			executeNextJob();
		}
		
		private function executeNextJob():void {
			if (_queue.isEmpty()) {
				_allJobsExecuted.dispatch(new EventArgs());
				return;
			}
			
			var item:JobItem =_queue.poll();
			
			item.job.execute(function(e:EventArgs):void {
				if (item.callback != null) {
					item.callback.call(null, e);
				}
				executeNextJob();	
			});
		}
	}
}
import com.proyecto404.core.IJob;

class JobItem {
	private var _job:IJob;
	private var _callback:Function;
	
	public function JobItem(job:IJob, callback:Function) {
		_job = job;
		_callback = callback;
	}	
	
	public function get job():IJob {
		return _job;
	}

	public function get callback():Function {
		return _callback;
	}
} 